import type { Next, Context } from 'koa';
import knex from '../utils/knex';
import _ from 'lodash';
import md5 from 'md5';
import { create } from '../utils/token';
import logger from '../utils/logger';

/**
 * @api {post} /auth/login 登录
 * @apiVersion 1.0.0
 * @apiDescription create by wuyanshen
 * @apiName login
 * @apiGroup 登录登出
 * @apiParam {string} username 用户名【必填】
 * @apiParam {string} password 密码【必填】
 * @apiUse authLoginSuccess
 * @apiUse authLoginError
 */
async function loginAction(ctx: Context, next: Next) {
    const { username, password } = ctx.request.body;
    // 查询用户信息
    const data = await knex('sys_user')
        .where({
            username: username,
        })
        .first();

    // 如果没查到用户
    if (_.isEmpty(data)) {
        ctx.fail(401, '用户名或密码错误');
        return next();
    }

    // 如果密码错误
    if (md5(password + username) !== data.password) {
        ctx.fail(401, '用户名或密码错误');
        return next();
    }

    // 如果账户停用
    if (data.status === '1') {
        ctx.fail(402, '您的账户已停用，请联系管理员');
        return next();
    }

    // 创建token
    const token = create({
        id: data.id,
        username: data.username,
    });

    const userInfo = {
        id: data.id,
        username: data.username,
    };

    ctx.user = userInfo;

    logger.info(`用户 ${data.username} 在${new Date().toLocaleString()} 进行了登录`);
    // 返回信息
    ctx.success(
        {
            userInfo: userInfo,
            token: token,
        },
        '登录成功',
    );
    return next();
}

/**
 * @api {post} /auth/logout 登出
 * @apiVersion 1.0.0
 * @apiDescription create by wuyanshen
 * @apiName logout
 * @apiGroup 登录登出
 * @apiUse authLogoutSuccess
 * @apiUse RequestError
 */
async function logoutAction(ctx: Context, next: Next) {
    ctx.success('退出成功');
    return next();
}

const authController = {
    loginAction,
    logoutAction,
};

export default authController;
